﻿package net.wangit.dev.unit;

import java.util.List;

import net.wangit.context.ActionContext;
import net.wangit.dev.ColumnRowUtil;
import net.wangit.dev.DomainAction;
import net.wangit.dev.LockUtil;
import net.wangit.dev.VersionUtil;
import net.wangit.dev.version.UnitVersion;
import net.wangit.dev.version.Version;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;


public class SaveJRAction extends DomainAction {

	private static Version version = new UnitVersion();

	public SaveJRAction() {
	}

	public void doAction(DB db, ActionContext ac) throws Exception {
		String oldUnitId = ac.getRequestParameter("jr.uid.k");
		String newUnitId = ac.getRequestParameter("jr.uid");
		if (!Checker.isEmpty(newUnitId))
			newUnitId = StringUtil.clearSpace(newUnitId.toLowerCase());
		format(ac, newUnitId);
		super.doAction(db, ac);
		ac.setSessionAttribute(JRUI.KEY, newUnitId);
		UnitCacheUtil.clearAll(domain, oldUnitId);
		UnitReferenceUtil.update(db, domain, oldUnitId, newUnitId);
		VersionUtil.saveVersion(ac, version, domain, newUnitId);
	}

	private void format(ActionContext ac, String unitId) {
		List<Table> tables = ac.getTables();
		if (tables.size() > 0) {
			Table table = tables.get(0);
			List<ColumnRow> rows = table.getRows();
			if (rows.size() > 0) {
				ColumnRow cRow = rows.get(0);
				cRow.set("uid", unitId);
				ColumnRowUtil.clearSpace(cRow, "d");
				ColumnRowUtil.clearSpace(cRow, "rs");
				ColumnRowUtil.clearSpace(cRow, "rw");
				LockUtil.setFields(ac, cRow, "jr");
			}
		}
	}

}
